import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import type Plan from './Plan.model';
import type Permission from './Permission.model';

class Tenant extends Model {
  public id!: string;
  public name!: string;
  public subdomain!: string;
  public planId!: string;
  public status!: string;
  public config?: any;
  public defaultPassword?: string; // 租户默认密码
  public trialEndsAt?: Date;
  public subscriptionEndsAt?: Date;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public deletedAt?: Date;

  // 关联属性
  public plan?: Plan;
  public permissions?: Permission[];

  isActive(): boolean {
    return this.status === 'active' || this.status === 'trial';
  }

  isTrialExpired(): boolean {
    if (!this.trialEndsAt) return false;
    return new Date() > this.trialEndsAt;
  }

  isSubscriptionExpired(): boolean {
    if (!this.subscriptionEndsAt) return false;
    return new Date() > this.subscriptionEndsAt;
  }
}

Tenant.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    subdomain: {
      type: DataTypes.STRING(63),
      allowNull: false,
      unique: true,
    },
    planId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'plan_id',
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'suspended', 'trial'),
      allowNull: false,
      defaultValue: 'trial',
    },
    config: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    defaultPassword: {
      type: DataTypes.STRING(255),
      allowNull: true,
      defaultValue: 'Pass123456', // 默认的初始密码
      field: 'default_password',
    },
    trialEndsAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'trial_ends_at',
    },
    subscriptionEndsAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'subscription_ends_at',
    },
  },
  {
    sequelize,
    tableName: 'tenants',
    underscored: true,
    paranoid: true,
    timestamps: true,
  },
);

export default Tenant;

